<template>
  <ElDrawer v-model="opened" :title="formType">
    <ElSkeleton v-if="loading" animated :rows="10" />
    <ElForm v-else ref="formRef" :model="form" :rules="rules" :disabled="isView" :label-width="80">
      <ElFormItem label="角色名称" prop="name">
        <ElInput placeholder="请输入角色名称" v-model="form.name" />
      </ElFormItem>
      <ElFormItem label="角色标识" prop="code">
        <ElInput placeholder="请输入角色标识" v-model="form.code" :disabled="!isAdd" />
      </ElFormItem>
      <ElFormItem label="角色描述" prop="desc">
        <ElInput placeholder="请输入角色描述" v-model="form.desc" type="textarea" :rows="3" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton v-if="!isView" type="primary" @click="onSaveClicked">保存</ElButton>
      <ElButton v-if="isView" @click="onCancelClicked">关闭</ElButton>
      <ElButton v-else @click="onCancelClicked">取消</ElButton>
    </template>
  </ElDrawer>
</template>

<script setup lang="ts">
import { reactive, ref, unref, computed } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { FormType } from '@/enums'
import { checkExist, getRole, addRole, updateRole } from '@api/uc/role'
import { Role } from '@api/uc/role/interface'
import { validateCode } from '@/utils/validator'
const formType = ref<FormType>()
const formRef = ref<FormInstance>()
const form = ref<Partial<Role.Form>>({})
const opened = ref(false)
const loading = ref(true)
const emit = defineEmits(['success'])

// 是否查看
const isView = computed(() => {
  return formType.value === FormType.VIEW
})

// 是否新增
const isAdd = computed(() => {
  return formType.value === FormType.ADD
})

// 重复校验
function validate(query: Role.CheckQuery, callback: any) {
  checkExist(query).then(resp => {
    if (resp.data) {
      callback(new Error('角色编码已存在'))
    } else {
      callback()
    }
  })
}

// 编码校验
function validateRepeatCode(rule: any, value: any, callback: any) {
  if (!value) {
    return callback()
  }
  const { id, code } = unref(form)
  validate({ id, code }, callback)
}

const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { max: 64, message: '角色名称最大 64', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { max: 64, message: '角色编码最大字符 64', trigger: 'blur' },
    { validator: validateCode, trigger: 'blur' },
    { validator: validateRepeatCode, trigger: 'blur' }
  ],
  desc: [{ max: 255, message: '角色描述最大 255', trigger: 'blur' }]
})

// 打开表单
async function open(type: FormType, id?: string) {
  formType.value = type
  opened.value = true
  if (isAdd.value) {
    loading.value = false
    form.value = {}
  } else {
    try {
      const { data } = await getRole(id!)
      loading.value = false
      form.value = data
    } finally {
      loading.value = false
    }
  }
  formRef.value?.clearValidate()
}

// 关闭表单
function close() {
  loading.value = true
  opened.value = false
}

// 保存按钮
function onSaveClicked() {
  if (!formRef.value) return
  formRef.value?.validate(valid => {
    if (!valid) {
      return
    }
    const menu = Object.assign({}, unref(form))
    if (isAdd.value) {
      addRole(menu).then(() => {
        success()
        sendSuccess()
        close()
      })
    } else {
      updateRole(menu).then(() => {
        success()
        sendSuccess()
        close()
      })
    }
  })
}

// 成功弹出提示
function success() {
  ElMessage({
    type: 'success',
    message: `成功!`
  })
}

// 取消按钮
function onCancelClicked() {
  close()
}

// 保存成功发送成功事件
function sendSuccess() {
  emit('success')
}

defineExpose({
  open,
  close
})
</script>
